//
//  NetworkTools.swift
//  微博009
//
//  Created by Romeo on 15/9/1.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import AFNetworking
import ReactiveCocoa

enum RequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

/// 网络工具类
class NetworkTools: AFHTTPSessionManager {

    // MARK: - App 信息
    private let clientId = "1407267207"
    private let appSecret = "6b66590f29bad6e7e7dd4c7b0c4dfa50"
    /// 回调地址
    let redirectUri = "http://www.baidu.com"
    
    /// 单例
    static let sharedTools: NetworkTools = {
        
        // 指定 baseURL
        var instance = NetworkTools(baseURL: nil)
        
        // 设置反序列化的支持格式
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    // MARK: - OAuth
    /// OAuth 授权 URL
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthUrl: NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        
        return NSURL(string: urlString)!
    }
    
    /// 获取 AccessToken
    ///
    /// - parameter code: 请求码/授权码
    /// - see: [http://open.weibo.com/wiki/OAuth2/access_token](http://open.weibo.com/wiki/OAuth2/access_token)
    func loadAccessToken(code: String) -> RACSignal {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        
        return request(.POST, URLString: urlString, parameters: params)
    }
    
    /// 网络请求方法
    ///
    /// - parameter method:     method
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    ///
    /// - returns: RAC Signal
    func request(method: RequestMethod, URLString: String, parameters: [String: AnyObject]?) -> RACSignal {
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
            // 1. 成功的回调闭包
            let successCallBack = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
                // 将结果发送给订阅者
                subscriber.sendNext(result)
                // 完成
                subscriber.sendCompleted()
            }
            
            // 2. 失败的回调闭包
            let failureCallBack = { (task: NSURLSessionDataTask, error: NSError) -> Void in
                print(error)
                subscriber.sendError(error)
            }
            
            // 3. 根据方法，选择调用不同的网络方法
            // if method == RequestMethod.GET {
            if method == .GET {
                self.GET(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            } else {
                self.POST(URLString, parameters: parameters, success: successCallBack, failure: failureCallBack)
            }
            
            return nil
        })
    }
}
